// ===============================================================================
// scan: sequential scan of a large descriptor collection
// Created in September 2007 as a project for an Advanced Database Systems course
// (c) Reykjavik University, Björn Þór Jónsson, Kristleifur Daðason, Herwig Lejsek
// Contact author: Björn Þór Jónsson, Reykjavík University, bjorn@ru.is
// ===============================================================================

#include "ClusterMapper.h"

ClusterMapper::ClusterMapper(ConfigMapper *cnfg, 
			     IndexEntry *entry,
			     FILE *datafile)
{
	cluster = entry;
	config  = cnfg;
	file    = datafile;
	mapped  = false;

	descByteSize = getFlexDescByteSize(config->getNumDims());
	scanNext = -1;
};

ClusterMapper::~ClusterMapper()
{
	if (mapped)
		close();
};

int ClusterMapper::getNumDescriptors()
{
	return cluster->size;
};

void ClusterMapper::open()
{
	// reset desc count;
	scanNext = 0;

	// Calculate the part of the file to map
	int mapStart  = cluster->offset * config->getPageSize();
	int mapLength = cluster->pages  * config->getPageSize();
	
	mapPtr = (unsigned char*) malloc(mapLength);
	fseek(file, mapStart,SEEK_SET);
	fread(mapPtr, mapLength, 1, file);
}

void ClusterMapper::close()
{
	free(mapPtr);
};

FlexDescriptor* ClusterMapper::next()
{
	if (scanNext == cluster->size)
		return NULL;

	off_t offset = scanNext++ * descByteSize;
	return (FlexDescriptor *)(mapPtr+offset);
};
